import { useEffect, useState, useRef } from "react";

export const isFalsy = (value: unknown) => {
  return value === 0 ? true : !!value;
};
export const isVoid = (value: unknown) => {
  return value === undefined || value === "" || value === null || value === 0;
};
export const cleanObject = (object: { [key: string]: unknown }) => {
  const result = { ...object };
  console.log("过滤前的参数===", result);
  Object.keys(result).forEach((key: string) => {
    if (isVoid(result[key])) {
      //@ts-ignore
      delete result[key];
    }
  });
  console.log("过滤后的参数===", result);
  return result;
};

export const queryStr = (obj: object) => {
  const str = Object.entries(obj)
    .map(([key, value]) => {
      return `${key}=${value}`;
    })
    .join("&");
  return str;
};

export const useMount = (callback: () => void) => {
  //hook只能在其他hook或组件中运行，不能在函数中运行
  useEffect(() => {
    callback();
  }, []);
};

const debounce = (fnc: (...param: any[]) => void, delay: number) => {
  let timeout: any;
  return (...param: any[]) => {
    if (timeout) {
      clearTimeout(timeout);
    }
    timeout = setTimeout(() => {
      fnc(...param);
    }, delay);
  };
};

export const useDebounce = <V>(value: V) => {
  const [debounceValue, setDebounceValue] = useState(value);
  console.log("输入后的值", value);
  useEffect(() => {
    //每次value变化后，设置一个定时器
    const timeout = setTimeout(() => {
      setDebounceValue(value);
      console.log("2秒后的值", debounceValue);
    }, 2000);
    //每当上一个effect执行完后，执行清理定时器的动作，
    //不能直接return clearTimeout，要返回待执行函数
    return () => clearTimeout(timeout);
  }, [value]);
  return debounceValue;
};

export const useArray = <A>(initialArray: A[]) => {
  const [value, setValue] = useState(initialArray);
  return {
    value,
    setValue,
    add: (item: A) => {
      return [...value, item];
    },
    clear: () => setValue([]),
    removeIndex: (index: number) => {
      const copy = [...value]; //浅拷贝
      copy.splice(index, 1);
      setValue(copy);
    },
  };
};

export const useDocumentTitle = (
  title: string,
  keepOnUnmount: boolean = true,
) => {
  //项目入口的文件名，使用useRef可以整个生命周期都不变
  const oldTitle = useRef(document.title).current;
  useEffect(() => {
    document.title = title;
  }, [title]);
  useEffect(() => {
    return () => {
      if (!keepOnUnmount) {
        console.log('卸载时的oldTitle', oldTitle)
        document.title = oldTitle; //退出当前页面后的其他页面默认展示项目入口的文件名
      }
    };
  },[])
};

export const resetRoute = () => {
  window.location.href = window.location.origin
}

/**
 * 返回组件的挂载状态，如果还没挂载或者已经卸载，则返回false；反之，返回true
 */
export const useMountedRef = () => {
  const mountedRef = useRef(false)
  useEffect(() => {
    mountedRef.current = true
    return () => { mountedRef.current = false}
  })
  return mountedRef
}